package com.sync.syncmasterdata.dingrobot.service;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiV2UserGetbymobileRequest;
import com.dingtalk.api.response.OapiV2UserGetbymobileResponse;
import com.sync.syncmasterdata.util.AuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 钉钉应用 服务层
 */
@Service
@Slf4j
public class DingAPIService {

    @Autowired
    private DingUtilService dingUtilService;

    @Autowired
    private AuthUtil authUtil;

    /**
     * 通过手机号获取ding userid
     * 升级为专属版本后,接口进行调整
     * @return
     */
    public String getDingUseridByPhone(String phone){
        if(phone==null||phone.equals("")){
            return null;
        }
        try{
//            String access_token = this.dingUtilService.getToken();
            String access_token = authUtil.getCPTokenByTag("dingrobottag");
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
            OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
            req.setMobile(phone);
            req.setSupportExclusiveAccountSearch(true);
            OapiV2UserGetbymobileResponse rsp = client.execute(req, access_token);
            if (rsp.getErrcode() == 0 && rsp.getResult().getExclusiveAccountUseridList().size()>0) {
                return rsp.getResult().getExclusiveAccountUseridList().get(0);
            }else{
                log.info("返回异常:{}", rsp.getErrmsg());
                return null;
            }
        }catch (Exception ex){
            ex.printStackTrace();
            return null;
        }
    }

    /**
     * 批量转换 phone to userid (使用钉钉转换接口)
     * 改为专属版本后接口有所调整
     * @param phones
     * @return
     */
    public List<String> convertPhoneToUseridList(List<String> phones) {
        List<String> userIds = new ArrayList<>();
        if(phones.size()!=0){
            for (String s : phones) {
                String _id = getDingUseridByPhone(s);
                if(_id!=null){
                    userIds.add(_id);
                }
            }
            return userIds;
        }else{
            return null;
        }
    }
}
